﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using test;
using test.EF;
using BLL.XXB;
using TestHttpModules.Models;
using System.Text;
using TestHttpModules.Filters;
using Commons.Entity;
using Commons.Web;
namespace TestHttpModules.Controllers
{
    public class HomeController : Controller
    {
        private static Dictionary<string, int> stock = new Dictionary<string, int>();
        UserService userService = null;
        public HomeController()
        {
            if (!stock.ContainsKey("001"))
                stock.Add("001", 20);
            if (!stock.ContainsKey("002"))
                stock.Add("002", 30);
            if (!stock.ContainsKey("003"))
                stock.Add("003", 40);

            userService = new UserService();
        }
        public ActionResult Index()
        {
            ViewBag.MSG = ShowModules();
            ViewBag.Linq = userService.GetUser_Info();
            ShoppingCart cart = new ShoppingCart();
            cart.Add(new ShoppingCartItem { Id = "001", Quantity = 1, Name = "商品A" });
            cart.Add(new ShoppingCartItem { Id = "002", Quantity = 1, Name = "商品B" });
            cart.Add(new ShoppingCartItem { Id = "003", Quantity = 1, Name = "商品C" });
            return View(cart);
        }



        public ActionResult ProcessOrder(ShoppingCart cart)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var cartItem in cart)
            {
                if (!CheckStock(cartItem.Id, cartItem.Quantity))
                {
                    sb.Append(string.Format("{0}: {1};", cartItem.Name, stock[cartItem.Id]));
                }
            }
            if (string.IsNullOrEmpty(sb.ToString()))
            {
                return Content("alert('购物订单成功处理！');location.href='/Home/OrderSuccess'", "text/javascript");
            }
            string script = string.Format("alert('库存不足! ({0})');", sb.ToString().TrimEnd(';'));
            return Content(script, "text/javascript");
        }

        /// <summary>
        /// 输出一个文件
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderSuccess()
        {
            return File("/Content/Ecmall30.png", "image/png");
        }

        /// <summary>
        /// 是否超出库存总数
        /// </summary>
        /// <param name="id"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        private bool CheckStock(string id, int quantity)
        {

            return stock[id] >= quantity;

        }


        public ActionResult About()
        {
            return View();
        }
        [HttpPost]
        public ActionResult About(ShoppingCartItem form)
        {

            if (ModelState.IsValid)
            {

            }
            else
            {
                ModelState.AddModelError("", "操作失败");
            }
            return View();
        }
        public ActionResult TEST()
        {
            return View();
        }
        private string ShowModules()
        {
            HttpApplication app = HttpContext.ApplicationInstance; // 获取当前上下文的
            HttpModuleCollection moduleCollection = app.Modules; //获取所有Module集合 

            // 获取所有的 Module 名称 
            string[] moduleNames = moduleCollection.AllKeys;

            System.Text.StringBuilder results = new System.Text.StringBuilder();

            //遍历结果集 
            foreach (string name in moduleNames)
            {
                // 获得Module名称 
                results.Append("<b style='color:#800800'>名称：" + name + "</b><br />");
                // 获得Module类型 
                results.Append("类型：" + moduleCollection[name].ToString() + "<br />");
            }

            return results.ToString();

        }

        [ExceptionLogAttribute]
        public ActionResult Create()
        {

            return View();
        }
        [HttpPost]
        public ActionResult Create(ShoppingCart entity)
        {

            return View();
        }

        #region 头像上传相关
        public ActionResult UploadHeadPic()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UploadHeadPic(FormCollection formcollection)
        {
            //FileUpload _FileUploadWebServices = new FileUpload();
            //if (Request.Files.Count > 0)
            //{
            //    HttpPostedFileBase file = Request.Files[0];
            //    byte[] imgBt = new byte[file.ContentLength];
            //    //将接受到文件读到字节数组中
            //    file.InputStream.Read(imgBt, 0, file.ContentLength);
            //   // VMessage vm = _FileUploadWebServices.Image(UpLoadType.Image, imgBt);
            //    if (vm.IsComplete)
            //        ViewData.Model = vm[0].Replace("\"", "");
            //}
            return View();
        }
        #endregion


        /// <summary>
        /// 图像解析
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Image(string id)
        {
            string path = Server.MapPath("/content/themes/base/images/" + id + ".png");
            return File(path, "image/jpeg");
        }
        public ActionResult PDF(string id)
        {
            if (string.IsNullOrEmpty(id))
                return null;
            string path = Server.MapPath("/content/" + id + ".pdf");
            return File(path, "application/pdf");
        }
        [ValidateInput(false)]
        public ActionResult ErrorHandler(string err)
        {
            return View(err as object);
        }

    }
}
